<?php

function sky_seldulac_preprocess_user_profile($variables) {
  $account = &$variables['account'];
  $currency = array_shift(currencies_load());
  //add the users balances to the default profile page
  //Balance
  $variables['balances'] = show_balances($account, array_keys(currencies_load()));
  //Balance history
  $variables['balance_history'] = show_balance_history($account, array($currency->nid), $extent = 'limits', $since = 0);
  //Balance limits
  $variables['balance_ometer'] = show_balance_ometer($account, $currency->nid);

  $summary[] = $account->profile_responsibility ? '<h4>'.$account->profile_responsibility.'</h4>' : '';
  $summary[] = $account->profile_address ? '<pre>'.$account->profile_address.'</pre>' : '';
  $summary[] = $account->profile_phone1 ? "<strong>tel 1: </strong>$account->profile_phone1" : '';
  $summary[] = $account->profile_phone2 ? "<strong>tel 2: </strong>$account->profile_phone1" : '';
  //Contact
  $variables['summary'] = implode("\n<br />", $summary);
}

/*
 * Initialize theme settings
 */
if (is_null(theme_get_setting('sky_layout'))) {
  global $theme_key;
  // Save default theme settings
  $defaults = array(
    'sky_seldulac_breadcrumbs' => 0,
    'sky_seldulac_breadcrumbs_sep' => '&raquo;',
    'sky_seldulac_font' => 'lucida',
    'sky_seldulac_font_headings' => 'lucida',
    'sky_seldulac_font_size' => '12px',
    'sky_seldulac_header_height' => 'auto',
    'sky_seldulac_layout' => 'fluid_98',
    'sky_seldulac_title' => 1,
    'sky_seldulac_nav_alignment' => 'center',
    'sky_seldulac_sub_navigation_size' => '15em',
    'sky_seldulac_wireframe' => 0,
  );
  
  variable_set(
    str_replace('/', '_', 'theme_'. $theme_key .'_settings'),
    array_merge($defaults, theme_get_settings($theme_key))
  );
  // Force refresh of Drupal internals
  theme_get_setting('', TRUE);
}

// Theme Settings Generated CSS
$custom_css = file_directory_path() .'/sky/custom.css';
if (file_exists($custom_css)) {
  drupal_add_css($custom_css, 'theme', 'all', TRUE);
}

// Conditional stylesheets for IE
function _sky_conditional_stylesheets() {
  $output = "\n".'<!--[if IE 6.0]><link rel="stylesheet" href="'. base_path() . path_to_theme() .'/css/ie-6.css" type="text/css" media="all" charset="utf-8" /><![endif]-->'."\n";
  $output .= '<!--[if IE 7.0]><link rel="stylesheet" href="'. base_path() . path_to_theme() .'/css/ie-7.css" type="text/css" media="all" charset="utf-8" /><![endif]-->'."\n";
  return $output;
}

function sky_seldulac_preprocess_page(&$variables, $hook) {
  // Add a page title variable using the site slogan on the front page
  if (theme_get_setting('sky_title')) {
    if ($variables['is_front'] && !is_null(variable_get('site_name', ''))) {
      $variables['sky_title'] = variable_get('site_name', '');
    } else {
      $variables['sky_title'] =  drupal_get_title();
    }
  }
  
  // Add a transparent spacer image to the end of the footer message
  $variables['footer_message'] .= theme('image', path_to_theme() .'/images/transparent.gif', 'spacer', 'spacer', array('style' => 'height:2em;'));
 
  // How is the navigation aligned
  $navigation_alignment = theme_get_setting('sky_nav_alignment');
  
  // Prepare the menu markup for the Primary Links (make it a menu tree)
  $tree = menu_tree(variable_get('menu_primary_links_source', 'primary-links'));
  $variables['primary_links'] = '<div class="primary-links wrap-center">'. menu_tree('primary-links') .'</div>';

  // Include advanced theme classes.
  if (theme_get_setting('sky_themer_classes') == 1) {
    include('theme-classes.php');
    $variables['body_tag'] = '<body'. $variables['body_css'] .'>';
  }
  else {
    $variables['body_tag'] = '<body class="'. $variables['layout'] .'" dir = "rtl">';
  }
    
    $variables['cforge_footer'] = t('Site designed and hosted for free by !cforge, a non-profit association registered in Geneva, Switzerland.', array('!cforge' => l('Community Forge', 'http://communityforge.net')));
}


function sky_seldulac_preprocess_comment(&$variables, $hook) {
  $comment = $variables['comment'];
  $node = node_load($comment->nid);
  
  if ($node->type == 'forum') {
    // User information
    $accountid = $comment->uid;
    
    if ($accountid == 0) {
      // Anonymous User
      $variables['account']->name = $comment->name;
      $variables['account']->homepage = $comment->homepage;
    }
    else {
      // Authenticated User
      $variables['account'] = user_load(array('uid' => $comment->uid));
      $variables['joined'] = t('<abbr class="created" title="!microdate">@date</abbr>', array(
      '@date' => format_date($variables['account']->created, 'custom', "m/d/y"),
      '!microdate' => format_date($variables['account']->created, 'custom', "Y-m-d\TH:i:sO"),
      ));
    }
    
    // provide an icon for comment copy link
    $icon_path = path_to_theme() .'/images/icons/link.png';
    $icon = theme('image', $icon_path, 'Copy comment link', NULL, NULL, TRUE);
    
    // if there is no image, provide alternative text
    if (!$icon) {
      $icon = '#'. $comment->cid;
    }
    
    $variables['comment_link'] = l($icon, 'node/'. $comment->nid, array(
      'attributes' => array(
        'class' => 'copy-comment',
        'title' => 'Grab this comment\'s link',
        'onclick' => 'javascript:return false;',
      ),
      'fragment' => 'comment-'. $comment->cid,
      'html' => TRUE,
      )
    );
    
    $variables['name'] = theme('username', $variables['account']);
    $variables['user_status'] = _sky_user_status($comment->uid);
  }
}

/*
 * Sky button links theme function
 * Insertion of <span> tags, and additional classes for themers
 */
function _sky_button_links($links, $attributes) {
  $output = '';
  
  if (count($links) > 0) {
    $output = '<ul'. drupal_attributes($attributes) .'>';
    $num_links = count($links);
    $i = 0;
    
    foreach ($links as $key => $link) {
      $class = '';
      // Automatically add a class to each link and also to each <li>
      if (isset($link['attributes']) && isset($link['attributes']['class'])) {
        $link['attributes']['class'] .= ' '. $key;
      }
      else {
        $link['attributes']['class'] = $key;
      }
      
      // Add even/odd classes
      $stripe = $i % 2 ? 'even' : 'odd';
      $link['attributes']['class'] = empty($link['attributes']['class']) ? $stripe : ($link['attributes']['class'] .' '. $stripe);
      
      // Add fist/last classes
      if ($i == 0) {
        $link['attributes']['class'] = empty($link['attributes']['class']) ? 'first' : ($link['attributes']['class'] .' first');
      }
      elseif ($i == $num_links - 1) {
        $link['attributes']['class'] = empty($link['attributes']['class']) ? 'last' : ($link['attributes']['class'] .' last');
      }
      
      // Is the title HTML?
      $html = isset($link['html']) && $link['html'];
      
      // Initialize fragment and query variables.
      $link['query'] = isset($link['query']) ? $link['query'] : NULL;
      $link['fragment'] = isset($link['fragment']) ? $link['fragment'] : NULL;
      
      // Add an HTML class to help style the content
      if ($html) {
        $wrapper = TRUE;
        $link['attributes']['class'] = empty($link['attributes']['class']) ? 'mixed' : ($link['attributes']['class'] .' mixed');
      }
      
      // Add an wrapper to items without actual links class to help style the content
      if (!$link['href'] && !$html) {
        $wrapper = TRUE;
        $link['attributes']['class'] = empty($link['attributes']['class']) ? 'plain' : ($link['attributes']['class'] .' plain');
      }
      // Add even/odd stripes
      $output .= '<li class="'. $link['attributes']['class'] .'">';
      
      if (isset($link['href'])) {
        $output .= l('<span class="tr">&nbsp;</span><span class="tl">&nbsp;</span><em>'. $link['title'] .'</em><span class="bl">&nbsp;</span><span class="br">&nbsp;</span>', $link['href'], array(
          'attributes' => array(
            'class' => 'button',
            'title' => $link['attributes']['title'],
            ),
          'query' => $link['query'],
          'fragment' => $link['fragment'],
          'html' => TRUE,
          )
        );
      }
      else if ($wrapper && $link['title']) {
        //Some links are actually not links, but we wrap these in <span> for adding title and class attributes
        if (!$html) {
          $link['title'] = check_plain($link['title']);
        }
        if ($wrapper) {
          $output .= '<div class="button">';
        }
        $output .= '<span class="tr">&nbsp;</span><span class="tl">&nbsp;</span><div>'. $link['title'] .'</div><span class="bl">&nbsp;</span><span class="br">&nbsp;</span>';
        if ($wrapper) {
          $output .= '</div>';
        }
      }
      $i++;
      $output .= "</li>\n";
    }
    $output .= '</ul>';
  }
  return $output;
}

/* deleted because the corresponding icon wasnt there. perhaps I removed it. doh!
function sky_seldulac_feed_icon($url, $title) {
  if (!$title) {
    $title = t('Subscribe to this feed');
  }
  if ($image = theme('image', path_to_theme() .'/images/feed.png', t('Syndicate content'), $title)) {
    return '<a href="'. check_url($url) .'" class="feed-icon">'. $image .'</a>';
  }
}*/

/*
 * Modification of core's theme_table();
 * Added a wrapper <div> with overflow to system generated tables
 * to deal <td> contents and the fact they they will not wrap or word-break
 */
function sky_seldulac_table($header, $rows, $attributes = array(), $caption = NULL) {

  // Add sticky headers, if applicable.
  if (count($header)) {
    drupal_add_js('misc/tableheader.js');
    // Add 'sticky-enabled' class to the table to identify it for JS.
    // This is needed to target tables constructed by this function.
    $attributes['class'] = empty($attributes['class']) ? 'sticky-enabled' : ($attributes['class'] .' sticky-enabled');
  }

  $output = '<div class="table-wrapper">';
  $output .= '<table'. drupal_attributes($attributes) .">\n";

  if (isset($caption)) {
    $output .= '<caption>'. $caption ."</caption>\n";
  }

  // Format the table header:
  if (count($header)) {
    $ts = tablesort_init($header);
    // HTML requires that the thead tag has tr tags in it follwed by tbody
    // tags. Using ternary operator to check and see if we have any rows.
    $output .= (count($rows) ? ' <thead><tr>' : ' <tr>');
    foreach ($header as $cell) {
      $cell = tablesort_header($cell, $header, $ts);
      $output .= _theme_table_cell($cell, TRUE);
    }
    // Using ternary operator to close the tags based on whether or not there are rows
    $output .= (count($rows) ? " </tr></thead>\n" : "</tr>\n");
  }
  else {
    $ts = array();
  }

  // Format the table rows:
  if (count($rows)) {
    $output .= "<tbody>\n";
    $flip = array('even' => 'odd', 'odd' => 'even');
    $class = 'even';
    foreach ($rows as $number => $row) {
      $attributes = array();

      // Check if we're dealing with a simple or complex row
      if (isset($row['data'])) {
        foreach ($row as $key => $value) {
          if ($key == 'data') {
            $cells = $value;
          }
          else {
            $attributes[$key] = $value;
          }
        }
      }
      else {
        $cells = $row;
      }
      if (count($cells)) {
        // Add odd/even class
        $class = $flip[$class];
        if (isset($attributes['class'])) {
          $attributes['class'] .= ' '. $class;
        }
        else {
          $attributes['class'] = $class;
        }

        // Build row
        $output .= ' <tr'. drupal_attributes($attributes) .'>';
        $i = 0;
        foreach ($cells as $cell) {
          $cell = tablesort_cell($cell, $header, $ts, $i++);
          $output .= _theme_table_cell($cell);
        }
        $output .= " </tr>\n";
      }
    }
    $output .= "</tbody>\n";
  }

  $output .= "</table>\n";
  $output .= '</div>';
  return $output;
}


/**
 * Returns the rendered local tasks. The default implementation renders
 * them as tabs.
 *
 * @ingroup themeable
 */
function sky_seldulac_menu_local_tasks() {
  
  $primary = menu_primary_local_tasks();
  $secondary = menu_secondary_local_tasks();
  
  if ($primary || $secondary) {
    $output = '<div class="tab-wrapper">';
    if ($primary) {
      $output .= "\n".'<div class="tabs-primary">'."\n".
      '  <ul>'."\n". $primary .'</ul>'."\n".
      '</div>';
    }
    if ($secondary) {
      $output .= "\n".'<div class="tabs-secondary">'."\n" .
      '  <ul>'."\n". $secondary .'</ul>'."\n" .
      '</div>';
    }
    $output .= '</div>';
  }
  
  return $output;
}

/*
 * Gets a users online status for the forum nodes/comments
 */
function _sky_user_status($uid) {
  if ($uid > 0) {
    $time_period = variable_get('user_block_seconds_online', 600);
    $users = db_query('SELECT DISTINCT (uid), access FROM {users} WHERE access >= %d AND uid = "%s"', time() - $time_period, $uid);
    $status = db_result($users);
    if ($status) {
      return TRUE;
    }
  }
}

/*
 * Class/ID String Filter (borrowed from zen)
 */
function _sky_id_safe($string) {
  if (is_numeric($string{0})) {
    // If the first character is numeric, add 'n' in front
    $string = 'n'. $string;
  }
  return strtolower(preg_replace('/[^a-zA-Z0-9-]+/', '-', $string));
}

function sky_seldulac_username($account) {
  if (!$account->uid) check_plain(variable_get('anonymous', t('Anonymous')));
  if (!$users[$account->uid]) {
    if (!$account->profile_firstname && !$account->profile_familyname) {
       $account = user_load($account->uid);
    }
    if (user_access('view all balances')) {
	  global $user;
	  static $users;
	  //get the printable name
	  if ($account->profile_firstname && $account->profile_familyname) {
        $name = $account->profile_firstname .' '. $account->profile_familyname;    
      }
	  else {
	    $name = $account->name;
      }
      //prepare the link, or not, and put in the static array
      if (user_access('access user profiles') && $GLOBALS['user']->uid <> $account->uid) {
	    $users[$account->uid] = l($name, 'user/'. $account->uid, array('attributes' => array('title' => t('View member profile.')))); 
	  }
      else {
        $users[$account->uid] = check_plain($name);
      }
    }
    //in case user mustn'y see names
    else {
      $users[$account->uid] = t("Member @uid", array("@uid" => $account->uid));
	}
  }
  return $users[$account->uid];
}

function sky_seldulac_imagecache($presetname, $path, $alt = '', $title = '', $attributes = NULL, $getsize = TRUE) {
  // Check is_null() so people can intentionally pass an empty array of
  // to override the defaults completely.
  if (is_null($attributes)) {
    $attributes = array('class' => 'imagecache imagecache-'. $presetname);
  }
  if ($getsize && ($image = image_get_info(imagecache_create_path($presetname, $path)))) {
    $attributes['width'] = $image['width'];
    $attributes['height'] = $image['height'];
  }

  $attributes = drupal_attributes($attributes);
  $imagecache_url = imagecache_create_url($presetname, $path);
  //added by matslats to help refresh pics after they've been changed
  if (arg(0)=='user') $imagecache_url .= '?';
  return '<img src="'. $imagecache_url .'" alt="'. check_plain($alt) .'" title="'. check_plain($title) .'" '. $attributes .' />';
}

function sky_seldulac_image_attach_attached_images_node($nid, $image_nodes, $img_size, $teaser = FALSE) {
  drupal_add_css(drupal_get_path('module', 'image_attach') . '/image_attach.css');

  $options = array(
    'size' => $img_size,
    'link' => $teaser ? 'node' : 'image',
    'attributes' => array(
      'class' => 'image-attach-' . ($teaser ? 'teaser' : 'body'),
    ),
  );

  // We take the images in reverse order because they are floated to the right,
  // and we want the apparent left to right order to be correct.
  $output = theme('image_attach_attached_images', $nid, array_reverse($image_nodes), $options);

  // Wrap output of potentially multiple images in a DIV.
  if ($output && !$teaser) {
    $output = '<div class="all-attached-images" style="float:right">' . $output . '</div>';
  }

  return $output;
}
